const hre = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
  const Crowdfunding = await hre.ethers.getContractFactory("Crowdfunding");
  const crowdfunding = await Crowdfunding.deploy();
  await crowdfunding.waitForDeployment();
  const contractAddress = crowdfunding.target;
  console.log("Crowdfunding deployed to:", contractAddress);
  
  // 获取合约ABI
  const contractArtifact = await hre.artifacts.readArtifact("Crowdfunding");
  const contractABI = contractArtifact.abi;
  
  // 更新前端配置文件
  const utilsPath = path.join(__dirname, "..", "..", "front", "src", "utils", "crowdfunding.js");
  let utilsContent = fs.readFileSync(utilsPath, "utf8");
  
  // 更新合约地址
  const addressRegex = /export const CONTRACT_ADDRESS = ['"].*?['"];?/;
  utilsContent = utilsContent.replace(addressRegex, `export const CONTRACT_ADDRESS = '${contractAddress}';`);
  
  // 更新合约ABI
  const abiRegex = /export const CONTRACT_ABI = \[[\s\S]*?\];/;
  utilsContent = utilsContent.replace(abiRegex, `export const CONTRACT_ABI = ${JSON.stringify(contractABI, null, 2)};`);
  
  // 写回文件
  fs.writeFileSync(utilsPath, utilsContent);
  console.log("Frontend configuration updated with new contract address and ABI");
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
